package com.attendcollatesys.filters;

import com.attendcollatesys.mapper.EmployeeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Autowired
    EmployeeMapper employeeMapper;




    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {




        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

//        HttpSession session = request.getSession(true);
//        // 获取会话ID
//        String sessionId = session.getId();
//        System.out.println(sessionId);



        //跨域
        response.setHeader("Access-control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type,account");
        // 暴露token，这里一定要写，如果你的写法与我的相同，检查此行代码是否也添加了
        response.setHeader("Access-Control-Expose-Headers", "account");
        response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");



//        // 检查客户端 Cookie
//        String cookie=request.getHeader("cookie");
//        Cookie[] cookies = request.getCookies();
//        if (cookies == null) {
//            // 如果 Cookie 未启用，需要提示用户
//            response.getWriter().write("Please enable cookie!");
//            return;
//        }

        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        String Oneperson = request.getHeader("account");

        log.info("拦截到请求：{}",requestURI);



        if ("OPTIONS".equals(request.getMethod())) {
            // 进行我们定义的请求前，浏览器自动发起的options请求
//            System.out.println(request.getSession().getAttribute("account:"+"123457"));
//            System.out.println(request.getSession().getAttribute(Oneperson+":permission"));
//            System.out.println(" is options ，不处理");
            // 服务器正常接收，返回状态码，不响应其他内容
            response.setStatus(HttpStatus.ACCEPTED.value());
            return;
        } else {
//            System.out.println("非options，处理");

        }






        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"
        };


        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);


        //3、如果不需要处理，则直接放行
        if(check){
            //放行
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }


        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        String error = "{\"code\":403, \"msg\":\"无权限操作\"}";



        //4、判断登录状态，如果已登录，则直接放行
        //从session中取出用户，能取出来不为空则为登录

        if(request.getSession().getAttribute("account:"+Oneperson) != null   )
        {
            if ("2".equals((request.getSession().getAttribute(Oneperson+":permission")))){
//                log.info("1111用户已登录，用户为：{}",Oneperson+":"+request.getSession().getAttribute("account:"+Oneperson));
//                log.info("1111用户已登录，用户permission为：{}",Oneperson+":"+request.getSession().getAttribute(Oneperson+":permission"));

                filterChain.doFilter(request,response);
                return;
            }else{
//                log.info("22222用户已登录，用户为：{}",Oneperson+":"+request.getSession().getAttribute("account:"+Oneperson));
//                log.info("2222用2户已登录，用户permission为：{}",Oneperson+":"+request.getSession().getAttribute(Oneperson+":permission"));

                if (PATH_MATCHER.match("/excel/**", requestURI)){
                    PrintWriter out = response.getWriter();
                    out.write(error);
                    out.flush();
                    out.close();
                    return;
                }else{
                    filterChain.doFilter(request,response);
                    return;
                }
            }
        }else {
            if(Oneperson != null && !"".equals(Oneperson)){
                if ("2".equals(employeeMapper.selectPerssionByAccount(Oneperson))){
                    filterChain.doFilter(request,response);
                    return;
                }

            }else {
                log.info("找不到用户，用户为：{}",Oneperson);
                error = "{\"code\":401, \"msg\":\"需要登录后操作\"}";
                //response.getWriter().write(403);
                PrintWriter out = response.getWriter();
                out.write(error);
                out.flush();
                out.close();
            }

            return;
        }





    }

    public boolean check(String[] urls,String requestURI){
        //是否匹配到url中的数组元素，能则放行
        for (String url : urls) {
        //match:匹配方法
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }



}
